class RateCLI
  module Index
    def index(target)
      results = @client.list(target: target)
      if results.contents.empty?
        info "There's no #{target} to list yet"
      end
      page = 1
      total_page = (results.contents.size / Float(@per_page) + 0.5).round

      refresh = lambda do
        results = @client.list(target: target)
        if results.contents.empty?
          info "There's no #{target} to list yet"
        end
        page = 1
        total_page =  (results.contents.size / Float(@per_page) + 0.5).round
      end

      content_for_page = lambda do 
        page = [page, 1].max
        page = [page, total_page].min
        skip = (page-1)*@per_page
        results.contents[skip...(skip+@per_page)]
      end

      id2global = lambda do |id|
        (page-1)*@per_page + id
      end

      loop do
        contents = content_for_page.call

        table = nil
        case target
        when 'view' then
          table = harray2table(contents, %w{name uuid created class_count sample_count description open})
        when 'benchmark' then
          table = harray2table(contents, %w{name uuid created type view_uuid description open})
        when 'algorithm' then
          table = harray2table(contents, %w{name uuid created type protocal tag description open})
        when 'task' then
          table = harray2table(contents, %w{uuid auuid buuid progress created finished open})
        end
        
        table.title = "All #{humanplural(target)}".bright
        puts table

        print "Page: %s/%s ---- " % [page, total_page]

        choice = panel_choose(target)

        case choice
        when /d (\d)/ then
          delete(target, results.contents[id2global.call($1.to_i)-1])
          refresh.call
        when /i (\d)/ then
          r = show(target, results.contents[id2global.call($1.to_i)-1])
          refresh if r
        when '<' then page -= 1
        when '>' then page += 1
        when 'c' then 
          create(target)
          refresh.call
        when 'r' then 
          if target == 'task'
            run
            refresh.call
          end
        when 'b' then break
        else
          refresh.call
        end
      end
    end

    def panel_choose(target=nil)
      panel = "[#{'d'.color(:green)}]elete No. | [#{'i'.color(:green)}]nfo No. | < > | [#{('b').color(:yellow)}]ack"
      if target != 'task'
        panel += " [#{('c').color(:cyan)}]reate"
      end
      if target == 'task'
        panel += " | [#{Rainbow('r').red}]un"
      end
      puts panel
      return what = @sui.ask("Do what?")
    end
  end
end